/*
 * Created on Mar 21, 2010
 */
package ro.letsdoitromania.forms;

import javax.microedition.lcdui.*;
import com.mgmaps.app.APPCommands;
import com.mgmaps.tools.UITools;
import com.mgmaps.utils.LS;
import ro.letsdoitromania.LDIRCanvas;
import ro.letsdoitromania.LDIRMidlet;
import ro.letsdoitromania.LDIRSettings;
import ro.letsdoitromania.TrashPointData;

public class ViewList implements CommandListener {
  private List list;
  
  private static ViewList instance;
  
  public static ViewList getInstance() {
    if (instance == null)
      instance = new ViewList();
    return instance;
  }
  
  private ViewList() {
  }
  
  public List getList() {
    return list;
  }
  
  public void show() {
    list = UITools.buildList(list, LS.get("ldir.viewlist.title"), new String[0], null, 
        APPCommands.instance.selectCommand, 
        new Command[] { APPCommands.instance.backCommand }, this);
    
    populateList(0);
    
    Display.getDisplay(LDIRMidlet.instance).setCurrent(list);
  }
  
  public void populateList(int selected) {
    UITools.deleteAll(list);
    
    int sz = LDIRSettings.points.size();
    for (int i=0; i<sz; i++)
      list.append(LDIRSettings.points.elementAt(i).toString(), null);
      
    if (selected >= 0 && selected < sz)
      list.setSelectedIndex(selected, true);
    else if (sz > 0)
      list.setSelectedIndex(0, true);
  }
  
  public void commandAction(Command cmd, Displayable disp) {
    if (cmd == APPCommands.instance.selectCommand || cmd == List.SELECT_COMMAND) {
      int index = list.getSelectedIndex();
      TrashPointData tpd = (TrashPointData) LDIRSettings.points.elementAt(index);
      
      ViewForm.getInstance().show(tpd, list, new Command[] { APPCommands.instance.editCommand,
          APPCommands.instance.deleteCommand, APPCommands.instance.backCommand });
    }
    else if (cmd == APPCommands.instance.backCommand) {
      if (disp == list)
        Display.getDisplay(LDIRMidlet.instance).setCurrent(LDIRCanvas.instance);
      else
        Display.getDisplay(LDIRMidlet.instance).setCurrent(list);
    }
  }
}
